import React, { useEffect, useState } from "react";
import * as Icon from "@ant-design/icons";
import { Layout, Menu } from "antd";
import MenuConfig from "../../config";
import { useNavigate, useLocation } from "react-router-dom";
import { useDispatch } from "react-redux";

const { Sider } = Layout;
const iconToElement = (name) => React.createElement(Icon[name]);
const handleMenu = (menus) => {
  return menus.map((menu) => {
    return {
      key: menu.path,
      icon: iconToElement(menu.icon),
      label: menu.label,
      children: menu.children && handleMenu(menu.children),
    };
  });
};
const menus = handleMenu(MenuConfig);
const CommonAside = ({ collapsed }) => {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const location = useLocation();
  const selectMenu = (e) => {
    navigate(e.key);
    let menuInfo;
    MenuConfig.find((menu) => {
      if (menu.path === e.keyPath[e.keyPath.length - 1]) {
        menuInfo = menu;
        if (menu.children?.length) {
          menuInfo = menu.children.find((item) => item.path === e.key);
        }
      }
    });
    dispatch({ type: "tab/selectTabList", payload: menuInfo });
    dispatch({ type: "tab/setCurrentMenu", payload: menuInfo });
  };
  const [selectedKeys, setSelectedKeys] = useState([]);
  const reloadMenu = () => {
    setSelectedKeys([location.pathname]); // 刷新后菜单高亮未解决
    let menuInfo;
    let pathArr = location.pathname.split("/");
    let keyPath = pathArr
      .splice(1, pathArr.length - 1)
      .map((item) => `/${item}`);
    MenuConfig.find((menu) => {
      if (menu.path === keyPath[0]) {
        menuInfo = menu;
        if (menu.children?.length) {
          menuInfo = menu.children.find(
            (item) => item.path === location.pathname
          );
        }
      }
    });
    dispatch({ type: "tab/selectTabList", payload: menuInfo });
    dispatch({ type: "tab/setCurrentMenu", payload: menuInfo });
  };
  useEffect(() => {
    reloadMenu();
  }, []);

  return (
    <Sider trigger={null} collapsed={collapsed}>
      <h3 className="app-name">{collapsed ? "后台" : "通用后台管理系统"}</h3>
      <Menu
        theme="dark"
        mode="inline"
        defaultSelectedKeys={selectedKeys}
        items={menus}
        style={{ height: "100%" }}
        onClick={selectMenu}
      />
    </Sider>
  );
};

export default CommonAside;
